package cc.servlet;

import cc.util.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName: GoodsServlet
 * @Description: 商品控制器
 * @Author: 晓东√
 * @Date: 2024-09-03 14:27
 * @Version: 1.0
 **/
@WebServlet("/goods.action")
@MultipartConfig
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String goodsName = req.getParameter("goodsName");
        Integer price = Integer.parseInt(req.getParameter("price"));

        System.out.println(goodsName+"----------"+price);
        //获取Part对象
        Part reqPart = req.getPart("goodsImage");
        //指定上传路径
        String fileUploadUrl = req.getSession().getServletContext().getRealPath("upload/");
        //logger.debug("指定上传路径" + fileUploadUrl);
        System.out.println("指定上传路径" + fileUploadUrl);
        //file流判断文件夹是否存在
        File file = new File(fileUploadUrl);
        //判断上传路径是否存在，不存在新建目录
        if(!file.exists()){
            file.mkdir();
        }
        //获取上传文件名
        String fileName = FileUtil.jxFileName(reqPart);
        //将文件上传服务器
        reqPart.write(fileUploadUrl+File.separator+fileName);

        System.out.println("上传地址："+fileUploadUrl+File.separator+fileName);

        req.setAttribute("imageUrl","upload/"+fileName);

        req.getRequestDispatcher("image.jsp").forward(req,resp);

    }
}
